<?php
/* -----------------------------------------------------------------
 *                        Aveghe My Blog
 * -----------------------------------------------------------------
 * Aveghe My Blog: made your blog easy!
 * Copyright (C) 2008 Elia Contini
 * 
 * Aveghe My Blog is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * Aveghe My Blog is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 */

class PostController extends Zend_Controller_Action
	{
		protected $_flashMessenger = null;
		protected $preferences = null;
		protected $avegheNS = null;
		
		public function init()
			{
				
				// general settings
				$this->view->setEncoding('UTF-8');
				$this->view->addHelperPath('aveghe/views/helpers', 'Aveghe_View_Helper');
				
				// preferences
				$this->preferences = Zend_Registry::get('preferences');
				/*while(list($key, $value) = each($this->preferences))
							echo "$key : $value <br />"; die;*/
				
				// for report
				$this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
				$this->view->report = $this->_flashMessenger->getMessages();
				
				$this->avegheNS = new Zend_Session_Namespace('avegheNS');
			}
			
		public function viewAllAction()
			{
				$page =  (int) $this->_getParam('page');
				
				$posts = new Doc();
				
				$recordNum = $this->preferences['site_home_item_num'];
				$filesNum = $posts->countFiles();
				$offset = 0;
				if($page > 0)
					{
						$offset = $page * $recordNum;
					}
					
				$pageNum = ceil($filesNum / $recordNum);
				
				$this->view->pageNum = $pageNum;
				$this->view->currentPage = $page;
				
				$this->view->posts = $posts->getFilesWithLimit($offset, $recordNum);
				$this->view->categories = $posts->getDirectories();
				$this->view->preferences = $this->preferences;
			}
			
		public function viewAction()
			{
				$fileID = (int) $this->_getParam('id');
				$file = new Doc();
				$fileContent = $file->getFileWithAuthorInfo($fileID);
				
				// TODO - (Aveghe) fine control with exception
				if($fileID != 0 && isset($fileContent['document_id']))
					{
						$this->view->file = $fileContent;
						
						// comments: global and single check
						if($this->preferences['site_comments'] != 'disable' && $this->view->file['document_comments_enable'] == 1)
							{
								$comments = new Comment();
								$this->view->comments = $comments->getCommentsForFile($fileID);
								
								$init = array( 'author'         => '',
											   'author_email'   => '',
											   'author_website' => '',
											   'comment_text'   => ''
											 );
								
								if(isset($this->avegheNS->validationResult))
									$this->view->validationResult = $this->avegheNS->validationResult;
								else
									$this->view->validationResult = $init;
								
								$this->avegheNS->validationResult = $init;
							}
						
						// preferences
						$this->view->preferences = $this->preferences;
						$this->view->preferences['page_title'] = $this->view->file['document_name'];
						
						// category
						$this->view->categories = $file->getDirectories();
						$this->view->currentCategory = $this->view->file['document_parent_directory'];
					}
				else
					$this->_forward('view-all');
			}
			
		public function byCategoryAction()
			{
				$directoryID = (int) $this->_getParam('id');
				
				$posts = new Doc();
				
				// TODO - (Aveghe) offset fisso!
				$this->view->posts = $posts->getDirectoryFilesWithLimit($directoryID, 0, 10);
				$this->view->preferences = $this->preferences;
				$this->view->categories = $posts->getDirectories();
				$this->view->currentCategory = $directoryID;
			}
		
		public function addCommentAction()
			{
				// disable autorendering for this action only
        		$this->_helper->viewRenderer->setNoRender();
        		
        		// TODO - (Aveghe) controllo se i commenti sono disabilitati
        		$request = $this->getRequest();
        		
        		// TODO - (Aveghe) salvataggio dei campi corretti ed evidenziazione dei campi errati
        		if($request->isPost())
					{   
						// field validation
						$validationResult = array();
						$errors = 0;
						
						$fileID         = (int) $request->getPost('fileID');
						$author         = trim((string) $request->getPost('author'));
						$author_email   = trim((string) $request->getPost('author_email'));
						$author_website = trim((string) $request->getPost('author_website'));
						$comment_text   = trim((string) $request->getPost('comment_text'));
						
						// author name check
						if(strlen($author) < 4 || $author == '')
							{ 
								$this->_flashMessenger->addMessage('<p class="warning">Il campo nome deve essere lungo almeno 4 caratteri.</p>');
								$validationResult['author'] = '';
								$errors++;
							}
						else
							$validationResult['author'] = $author;
						
						// author email check
						$emailAddress = explode('@', $author_email);
						
						if(count($emailAddress) == 2 && strpos($author_email, ' ') === false && strpos($emailAddress[1], '.') > 1)
							$validationResult['author_email'] = $author_email;
						else
							{
								$this->_flashMessenger->addMessage('<p class="warning">L\'indirizzo e-mail non ha un formato valido.</p>');
								$validationResult['author_email'] = '';
								$errors++;
							}
						
						/*if(strpos($author_email, '@') === false || strpos($author_email, '.') === false || strpos($author_email, ' ') > 0)
							{
								$this->_flashMessenger->addMessage('<p class="warning">L\'indirizzo e-mail non ha un formato valido.</p>');
								$validationResult['author_email'] = '';
								$errors++;
							}
						else
							$validationResult['author_email'] = $author_email;*/

						// author website check
						if($author_website != '' && !ereg("^http://", $author_website))
							$author_website = 'http://'.$author_website;
							
						$validationResult['author_website'] = htmlspecialchars($author_website, ENT_QUOTES, 'UTF-8');
						
						// comment text check
						if($comment_text == '')
							{
								$this->_flashMessenger->addMessage('<p class="warning">Inserisci il testo del commento.</p>');
								$validationResult['comment_text'] = '';
								$errors++;
							}
						else
							$validationResult['comment_text'] = $comment_text;	

						$this->avegheNS->validationResult = $validationResult;
						
						
						if($errors != 0)
							{  
								$this->_redirect('post/view/id/'.$request->getPost('fileID').'#commentForm');
							}
						else
							{
								$comment = new Comment();
		        				$data = array( 'comment_file_id'        => $fileID,
		        							   'comment_author'         => $author,
		        							   'comment_author_email'   => $author_email,
		        							   'comment_author_website' => $author_website,
		        							   'comment_text'           => nl2br(htmlentities($comment_text, ENT_QUOTES, 'UTF-8')),
		        							   'comment_date'           => '',
		        							   'comment_user_agent'     => $_SERVER['HTTP_USER_AGENT'],
		        							   'comment_remote_ip'      => $_SERVER['REMOTE_ADDR']			   
		        					 		 );
		        				
		        				if($this->preferences['site_comments'] != 'enable')
		        					$data['comment_approved'] = 0;
		        				else
		        					$data['comment_approved'] = 1;
		        				
		        				$comment->insertUpdateComment(NULL, $data);
		        				
		        				$init = array( 'author' => '',
									   'author_email'   => '',
									   'author_website' => '',
									   'comment_text'   => ''
									 );
								$this->avegheNS->validationResult = $init;
								
								$this->_flashMessenger->addMessage('<p class="success">Il tuo commento &egrave; stato salvato ed &egrave; in attessa di essere moderato. Grazie per aver contribuito a far crescere il blog.</p>');
							}
					}
				
				$this->_redirect('post/view/id/'.$request->getPost('fileID').'#commentForm');
			}
	}
?>